package org.finegold.core.discern.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Splitter;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.finegold.core.discern.enums.BuildParams;
import org.finegold.core.discern.enums.CustomType;
import org.finegold.core.discern.enums.IdType;
import org.finegold.core.discern.enums.MethodType;
import org.finegold.core.discern.props.DiscernProperties;
import org.finegold.core.discern.service.IDiscernApi;
import org.finegold.core.http.HttpRequest;
import org.finegold.core.http.ResponseSpec;
import org.finegold.core.tool.api.R;
import org.finegold.core.tool.utils.Base64Util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.function.Consumer;

/**
 * <B>Description:</B> 接口调用
 *
 * @Author QinXueFeng
 * @Date 2020/9/10 9:48
 * @Version 1.0.10
 * @VersionList <pre>
 *    版本        修改人        修改日期        修改描述
 *    ------------------------------------------------------------
 *    1.0.10       QinXueFeng        2020/9/10 9:48        create
 *    ------------------------------------------------------------
 * </pre>
 */
@AllArgsConstructor
@Slf4j
public class DiscernApiImpl implements IDiscernApi {

	private DiscernProperties discernProperties;

	@Override
	public String img_base64(String path) {
		/**
		 *  对path进行判断，如果是本地文件就二进制读取并base64编码，如果是url,则返回
		 */
		String imgBase64 = "";
		if (path.startsWith("http")) {
			imgBase64 = path;
		} else {
			File file = new File(path);
			try (FileInputStream finputstream = new FileInputStream(file)) {
				byte[] content = new byte[(int) file.length()];
				finputstream.read(content);
				finputstream.close();
				imgBase64 = Base64Util.encodeToString(content);
			} catch (IOException e) {
				e.printStackTrace();
				return imgBase64;
			}
		}
		return imgBase64;
	}

	@SneakyThrows
	@Override
	public void asyncDiscern(String base64, MethodType methodType, IdType idType, CustomType customType, Consumer<ResponseSpec> consumer) {
		BuildParams buildParams = new BuildParams(methodType, idType, customType, discernProperties).invoke();
		Map<String, String> headers = buildParams.getHeaders();
		JSONObject jsonObject = buildParams.getJsonObject();
		// 拼装请求body的json字符串
		jsonObject.put("image", base64);
		String bodys = jsonObject.toString();
		HttpRequest.post(methodType.getUrl())
			.addHeader(headers)
			.bodyString(bodys)
			.async()
			.onFailed((request, e) -> {
				log.info("识别出错", e.getMessage(), e);
			}).onSuccessful(consumer);
	}

	@SneakyThrows
	@Override
	public R<String> Discern(String base64, MethodType methodType, IdType idType, CustomType customType) {
		BuildParams buildParams = new BuildParams(methodType, idType, customType, discernProperties).invoke();
		Map<String, String> headers = buildParams.getHeaders();
		JSONObject jsonObject = buildParams.getJsonObject();
		// 拼装请求body的json字符串
		jsonObject.put("image", base64);
		String bodys = jsonObject.toString();
		R<String> r = new R<String>();
		HttpRequest.post(methodType.getUrl())
			.addHeader(headers)
			.bodyString(bodys)
			.execute()
			.onFailed((request, e) -> {
				Map<String, String> map1 = Splitter.on(",").omitEmptyStrings().withKeyValueSeparator("=").split(e.getMessage());
				r.setCode(Integer.parseInt(map1.get(" code")));
				r.setMsg("请上传正确类别且清晰的图片!");
			}).onSuccessful((l) -> {
			r.setCode(l.code());
			r.setMsg(l.message());
			r.setData(l.asString());
			return r;
		});
		return r;
	}


}
